using AutoMapper;
using MediatR;
using S.O.Api.Write.Application.Command.Permission;
using S.O.Domain.RBAC;
using S.O.ErrorCode;
using S.O.Interstructrue.Base;

namespace S.O.Api.Write.Application.Handler.Permission
{
    /// <summary>
    /// 更新权限处理器
    /// 负责处理权限信息更新的业务逻辑
    /// </summary>
    public class UpdatePermissionHandler : IRequestHandler<UpdatePermissionCommand, APIResult<int>>
    {
        /// <summary>
        /// 权限仓储接口，用于权限数据的CRUD操作
        /// </summary>
        private readonly IBaseRepository<PermissionModel> permissionRepository;
        
        /// <summary>
        /// 对象映射器，用于Command对象到Model对象的转换
        /// </summary>
        private readonly IMapper mapper;
        
        /// <summary>
        /// 日志记录器，用于记录操作日志和错误信息
        /// </summary>
        private readonly ILogger<UpdatePermissionHandler> logger;

        /// <summary>
        /// 构造函数，通过依赖注入初始化所需的服务
        /// </summary>
        /// <param name="permissionRepository">权限仓储服务</param>
        /// <param name="mapper">对象映射服务</param>
        /// <param name="logger">日志记录服务</param>
        public UpdatePermissionHandler(IBaseRepository<PermissionModel> permissionRepository, IMapper mapper, ILogger<UpdatePermissionHandler> logger)
        {
            this.permissionRepository = permissionRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        
        /// <summary>
        /// 处理更新权限命令
        /// 执行权限信息更新操作
        /// </summary>
        /// <param name="request">更新权限命令对象，包含要更新的权限信息</param>
        /// <param name="cancellationToken">取消令牌，用于取消异步操作</param>
        /// <returns>返回包含操作结果的APIResult对象</returns>
        public Task<APIResult<int>> Handle(UpdatePermissionCommand request, CancellationToken cancellationToken)
        {
            // 初始化返回结果对象
            APIResult<int> res = new APIResult<int>();
            
            // 根据权限ID查找要更新的权限信息
            var model = permissionRepository.GetALL().FirstOrDefault(x => x.Id == request.Id);
            
            // 使用AutoMapper将请求对象的数据映射到权限实体对象
            var data = mapper.Map(request, model);
            
            // 执行权限信息更新操作
            var r = permissionRepository.Update(data);
            
            // 根据更新结果返回相应的响应
            if (r > 0)
            {
                res.Data = r;
                res.Code = APIEnums.Success;
                res.Msg = "修改成功";
                logger.LogInformation($"权限ID:{request.Id}更新成功");
                return Task.FromResult(res);
            }
            else
            {
                res.Code = APIEnums.Fail;
                res.Msg = "修改失败";
                logger.LogError($"权限ID:{request.Id}更新失败");
                return Task.FromResult(res);
            }
        }
    }
}
